package net.sk.china.city.talk.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageInfo;
import net.sk.china.city.talk.request.order.StoreOrderSearchRequest;
import net.sk.china.city.talk.request.product.StoreProductSearchRequest;
import net.sk.china.city.talk.response.order.OrderExcelResponse;
import net.sk.china.city.talk.response.order.StoreOrderDetailResponse;
import net.sk.china.city.talk.response.product.ProductExcelResponse;
import net.sk.china.city.talk.response.product.StoreProductResponse;
import net.sk.china.city.talk.service.CategoryService;
import net.sk.china.city.talk.service.ExcelService;
import net.sk.china.city.talk.service.order.StoreOrderService;
import net.sk.china.city.talk.service.product.StoreProductService;
import net.sk.china.common.config.TalkConfig;
import net.sk.china.common.constants.Constants;
import net.sk.china.common.exception.TalkException;
import net.sk.china.common.request.PageParamRequest;
import net.sk.china.common.response.CommonPage;
import net.sk.china.common.utils.DateUtil;
import net.sk.china.common.utils.ExportUtil;
import net.sk.china.common.utils.TalkUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ExcelServiceImpl 接口实现
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2018-2024 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2024/6/5 15:32
 * // +----------------------------------------------------------------------
 */

@Service
public class ExcelServiceImpl implements ExcelService {

    private final StoreProductService storeProductService;

    private final StoreOrderService storeOrderService;

    private final CategoryService categoryService;

    private final TalkConfig talkConfig;

    public ExcelServiceImpl(StoreProductService storeProductService, StoreOrderService storeOrderService, CategoryService categoryService, TalkConfig talkConfig) {
        this.storeProductService = storeProductService;
        this.storeOrderService = storeOrderService;
        this.categoryService = categoryService;
        this.talkConfig = talkConfig;
    }

    /**
     * 商品导出
     * @param request 请求参数
     * @return {@code String}
     */
    @Override
    public String exportProduct(StoreProductSearchRequest request) {
        PageParamRequest pageParamRequest = new PageParamRequest();
        pageParamRequest.setPage(Constants.DEFAULT_PAGE);
        pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
        PageInfo<StoreProductResponse> storeProductResponsePageInfo = storeProductService.getAdminList(request, pageParamRequest);
        List<StoreProductResponse> list = storeProductResponsePageInfo.getList();
        if(list.size() < 1){
            throw new TalkException("没有可导出的数据！");
        }

        //产品分类id
        List<String> cateIdListStr = list.stream().map(StoreProductResponse::getCateId).distinct().collect(Collectors.toList());

        HashMap<Integer, String> categoryNameList = new HashMap<>(8);
        if(cateIdListStr.size() > 0){
            String join = StringUtils.join(cateIdListStr, ",");
            List<Integer> cateIdList = TalkUtil.stringToArray(join);
            categoryNameList = categoryService.getListInId(cateIdList);
        }
        List<ProductExcelResponse> voList = CollUtil.newArrayList();
        for (StoreProductResponse product : list ) {
            ProductExcelResponse vo = new ProductExcelResponse();
            vo.setStoreName(product.getStoreName());
            vo.setStoreInfo(product.getStoreInfo());
            vo.setCateName(TalkUtil.getValueByIndex(categoryNameList, product.getCateId()));
            vo.setPrice("￥" + product.getPrice());
            vo.setStock(product.getStock().toString());
            vo.setSales(product.getSales().toString());
            vo.setBrowse(product.getBrowse().toString());
            voList.add(vo);
        }

        /**
         * ===============================
         * 以下为存储部分
         * ===============================
         */
        // 上传设置
        ExportUtil.setUpload(talkConfig.getUploadPath(), "excel", Constants.UPLOAD_TYPE_FILE);

        // 文件名
        String fileName = "商品导出_".concat(DateUtil.localDateTimeToString(DateUtil.getNowTime(), Constants.DATE_TIME_FORMAT_NUM)).concat(String.valueOf(TalkUtil.randomCount(111111111, 999999999))).concat(".xlsx");

        //自定义标题别名
        LinkedHashMap<String, String> aliasMap = new LinkedHashMap<>();
        aliasMap.put("storeName", "商品名称");
        aliasMap.put("storeInfo", "商品简介");
        aliasMap.put("cateName", "商品分类");
        aliasMap.put("price", "价格");
        aliasMap.put("stock", "库存");
        aliasMap.put("sales", "销量");
        aliasMap.put("browse", "浏览量");

        return ExportUtil.exportExecl(fileName, "商品导出", voList, aliasMap);
    }

    /**
     * 订单导出
     * @param request 查询条件
     * @return {@code String}
     */
    @Override
    public String exportOrder(StoreOrderSearchRequest request) {
        PageParamRequest pageParamRequest = new PageParamRequest();
        pageParamRequest.setPage(Constants.DEFAULT_PAGE);
        pageParamRequest.setLimit(Constants.EXPORT_MAX_LIMIT);
        CommonPage<StoreOrderDetailResponse> adminList = storeOrderService.getAdminList(request, pageParamRequest);
        List<StoreOrderDetailResponse> list = adminList.getList();
        if(list.size() < 1){
            throw new TalkException("没有可导出的数据！");
        }

        List<OrderExcelResponse> voList = CollUtil.newArrayList();
        for (StoreOrderDetailResponse order: list ) {
            OrderExcelResponse vo = new OrderExcelResponse();
            vo.setCreateTime(order.getCreateTime());
            vo.setOrderId(order.getOrderId());
            vo.setOrderType(order.getOrderType());
            vo.setPayPrice(order.getPayPrice().toString());
            vo.setPayTypeStr(order.getPayTypeStr());
            vo.setProductName(order.getProductList().stream().map(item-> item.getInfo().getProductName()).collect(Collectors.joining(",")));
            vo.setRealName(order.getRealName());
            vo.setStatusStr(order.getStatusStr().get("value"));
            voList.add(vo);
        }

        /*
          ===============================
          以下为存储部分
          ===============================
         */
        // 上传设置
        ExportUtil.setUpload(talkConfig.getUploadPath(), "excel", Constants.UPLOAD_TYPE_FILE);

        // 文件名
        String fileName = "订单导出_".concat(DateUtil.localDateTimeToString(DateUtil.getNowTime(), Constants.DATE_TIME_FORMAT_NUM)).concat(String.valueOf(TalkUtil.randomCount(111111111, 999999999))).concat(".xlsx");

        //自定义标题别名
        LinkedHashMap<String, String> aliasMap = new LinkedHashMap<>();
        aliasMap.put("orderId", "订单号");
        aliasMap.put("payPrice", "实际支付金额");
        aliasMap.put("createTime", "创建时间");
        aliasMap.put("productName", "商品信息");
        aliasMap.put("statusStr", "订单状态");
        aliasMap.put("payTypeStr", "支付方式");
        aliasMap.put("orderType", "订单类型");
        aliasMap.put("realName", "用户姓名");

        return ExportUtil.exportExecl(fileName, "订单导出", voList, aliasMap);

    }
}
